import { View, Image, Text, CoverImage, RichText } from '@tarojs/components'
import { useState, useEffect, useCallback } from 'react'
import LgButton from '../../components/button'
import LgInput from '../../components/input'
import LgCell from '../../components/cell'
import LgSwitch from '../../components/switch'
import { LgSlide } from '../../components/slides'
import { LgPopLayer } from '../../components/popLayer'
import Header from '../..//components/navCustomBar'
import Taro from '@tarojs/taro'
import moment from 'moment'
import Proxy from 'src/network/proxy'
import { requestSystemUrl } from 'src/network/baseUrl'
import { HttpGet, HttpPut, HttpPost, HttpDelete } from '../../../network/servers'
import Utils from '../../../utils/index'
import { connect } from 'react-redux'
import { getBrowserController, getNet, getStorage, getWxSDKParams } from '../../components/utils';
import { CalendarPicker, List, Popup, VirtualInput, Input, SearchBar, Picker, Button, DatePicker, Toast } from 'antd-mobile'
import dayjs from 'dayjs'
import '../../images/public/style.css'
import './index.scss'
import _ from 'lodash'

const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
function timeToString(timeObj) {
  var str = "";
  var year = timeObj.getFullYear();
  var month = timeObj.getMonth() + 1;
  var date = timeObj.getDate();
  if (month < 10) {
    month = '0' + month
  }
  if (date < 10) {
    date = '0' + date
  }
  str = year + "/" + month + "/" + date
  return str;
}

//计算两天之间间隔的日期
function getDayAll(starDay, endDay) {

  var arr = [];
  var dates = [];

  // 设置两个日期UTC时间
  var db = new Date(starDay);
  var de = new Date(endDay);

  // 获取两个日期GTM时间
  var s = db.getTime() - 24 * 60 * 60 * 1000;
  var d = de.getTime() - 24 * 60 * 60 * 1000;

  // 获取到两个日期之间的每一天的毫秒数
  for (var i = s; i <= d;) {
    i = i + 24 * 60 * 60 * 1000;
    arr.push(parseInt(i))
  }

  // 获取每一天的时间  YY-MM-DD
  let index = 0
  for (var j in arr) {
    var time = new Date(arr[j]);
    var year = time.getFullYear(time);
    var mouth = (time.getMonth() + 1) >= 10 ? (time.getMonth() + 1) : ('0' + (time.getMonth() + 1));
    var day = time.getDate() >= 10 ? time.getDate() : ('0' + time.getDate());
    var YYMMDD = year + '-' + mouth + '-' + day;
    let obj = {
      planDate: YYMMDD,
      saveWeeklyPlanBoList: [],
      index
    }
    index = index + 1
    dates.push(obj)
  }

  return dates
}

const storage = getStorage()
var wx = require('weixin-js-sdk')
const {
  getNowToken,
  getQueryVariable,
} = Utils


const requireContext = require.context("../../images/fileIcon", true, /^\.\/.*\.svg$/);
const svgs = requireContext.keys().map(requireContext);
const keys = requireContext.keys()
let fileObj = {}

keys.map((item, index) => {
  let str = item.replace('./', "").replace('.svg', "")
  fileObj[str] = svgs[index]
})


let nowArrangeIndex = 0

function App(props) {

  let {
    noticeAddr,
    userInfo,
    env,
    baseUrl,
    systemInfo1
  } = props

  const getToken = () => {
    if (getQueryVariable('env') == 'weapp') {
      return getQueryVariable('lg_tk')
    } else {
      return storage.get('token') || getQueryVariable('lg_tk')
    }
  }



  const [detail, setDetail] = useState(null);
  const [fileList, setFileList] = useState([]);
  const [imgList, setImgList] = useState([]);

  const [newsId, setNewsId] = useState("");
  const [taskId, setTaskId] = useState('')

  const [isRead, setIsRead] = useState(0);
  const [type, setType] = useState('0');
  const [height, setHeight] = useState(0);

  const [title, setTitle] = useState('')
  const [content, setContent] = useState('')
  const [cover, setCover] = useState('')
  //2023
  const [contentPageList, setContentPageList] = useState<any>([])
  const [typeList, setTypeList] = useState([])
  const [visible, setVisible] = useState(false)
  const [typeId, setTypeId] = useState('')
  const [typeName, setTypeName] = useState('')

  const [systemInfo, setSystemInfo] = useState(systemInfo1)
  const [toEdu, setToEdu] = useState(false)

  const [inputPopOpen, setInputPopOpen] = useState(false)//2023-10-08 增加类型修改功能
  const [inputPopOpenNew, setInputPopOpenNew] = useState(false)//2023-10-09 新增类型
  const [oldValue, setOldValue] = useState('')//2023-10-08 类型旧名称
  const [oldItem, setOldItem] = useState('')//2023-10-08 保存所修改的某条类型

  const [arrange_data, setArrange_data] = useState([])

  const [timeValue, setTimeValue] = useState("")



  // const changeTime = useCallback((val, index) => {
  //   temp_saveWeeklyPlanBoList[index].time = val
  // }, [temp_saveWeeklyPlanBoList])


  const getCommonData = () => {
    if (Utils.getQueryVariable('env') == 'weapp' || window.__wxjs_environment == 'miniprogram') {
      // 小程序端的h5
      if (!baseUrl) {
        // 直接跳转当前页面

      } else {
        console.log('小程序');

        //应用内跳转
        let instance = Taro.getCurrentInstance()
        if (instance.router?.params) {
          let params = instance.router.params
          let id = params.id
          if (!id) return;
          // console.log(params);
          setIsRead(isRead)
          setNewsId(id)

          let url = "/api/news/info//edit/detailed"
          HttpGet({
            url,
            data: {
              newsId: id,
            }
          }).then(res => {
            if (res.code == 200 && res.data) {
              let data = res.data
              console.log(data.newsCoverPath, 'data.newsCoverPath');

              setTitle(data.newsTitle)
              // setContent((data.newsContent).replace(/<[^>]*>|<\/[^>]*>/gm, ""))
              setContent(data.newsContent)
              setCover(JSON.parse(JSON.stringify(data.newsCoverPath)))
              setTypeId(data.newsTypeId)
              setTypeName(data.newsTypeName)
              let attachments = res.data.newsAttachmentVoList
              if (attachments && attachments.length !== 0) {
                let imgArr = [], fileArr = [];
                attachments.map(item => {
                  let fileType = Utils.getFileType(item?.attachmentName)
                  if (fileType == 'img') {
                    item.url = item.attachmentUrl
                    item.size = item.attachmentSize
                    item.fileName = item.attachmentName
                    imgArr.push(item)
                  } else {
                    item.url = item.attachmentUrl
                    item.size = item.attachmentSize
                    item.fileName = item.attachmentName
                    fileArr.push(item)
                  }
                })

                setFileList(fileArr)
                setImgList(imgArr)
              }
              setIsRead(res.data.readStatus)
              setDetail(res.data)
            } else {
              Taro.showToast({
                title: res.msg,
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      }
    } else {
      // app内 1.应用内跳转(不需要获取通知地址和用户信息) 2.直接跳转
      let instance = Taro.getCurrentInstance()

      const browserController = getBrowserController()
      let height = browserController.getStatusBarHeight()
      setHeight(height)
      if (instance.router?.params && instance.router?.params.weeklyRoutineId != 0) {
        let params = instance.router.params
        console.log(params)
        let id = params.id
        if (!id) return;
        // console.log(params);

        setIsRead(isRead)
        setNewsId(id)

        HttpGet({
          // url: '/api/commons/school/user/self',
          url: `api/common/user`,
          data: {
            token: getNowToken()
          },

        }).then((res1) => {
          HttpGet({
            // url: 'api/commons/system/server/info',
            url: 'api/common/system/list',
            data: {
              sysIds: '220',
            },
          }).then((response) => {
            let url = response.data.webSvrAddr + "/api/news/info//edit/detailed"
            HttpGet({
              url,
              data: {
                newsId: id,
              }
            }).then(res => {
              if (res.code == 200 && res.data) {
                let data = res.data
                console.log(data.newsCoverPath, 'data.newsCoverPath');

                setTitle(data.newsTitle)
                // setContent((data.newsContent).replace(/<[^>]*>|<\/[^>]*>/gm, ""))
                setContent(data.newsContent)
                setCover(JSON.parse(JSON.stringify(data.newsCoverPath)))
                setTypeId(data.newsTypeId)
                setTypeName(data.newsTypeName)
                let attachments = res.data.newsAttachmentVoList
                if (attachments && attachments.length !== 0) {
                  let imgArr = [], fileArr = [];
                  attachments.map(item => {
                    let fileType = Utils.getFileType(item?.attachmentName)
                    if (fileType == 'img') {
                      item.url = item.attachmentUrl
                      item.size = item.attachmentSize
                      item.fileName = item.attachmentName
                      imgArr.push(item)
                    } else {
                      item.url = item.attachmentUrl
                      item.size = item.attachmentSize
                      item.fileName = item.attachmentName
                      fileArr.push(item)
                    }
                  })

                  setFileList(fileArr)
                  setImgList(imgArr)
                }
                setIsRead(res.data.readStatus)
                setDetail(res.data)
              } else {
                Taro.showToast({
                  title: res.msg,
                  icon: 'none',
                  duration: 2000
                })
              }
            })
          })
        })
      }
    }
  }

  const [edit_add, setEdit_add] = useState('')
  const [detail_data, setDetail_data] = useState({})
  //获取详情数据
  const getDetailData = (params) => {
    let url = 'api/weekly/general/info/detail'
    HttpGet({
      url,
      data: {
        weeklyRoutineId: params,
      }
    }).then((res) => {
      if (res.code == 200) {
        let data = res.data
        let arr: any[] = []
        data.generalWeeklyPlanVoList.forEach(i => {
          if (arr.length == 0) {
            arr.push({
              planDate: i.planDate.slice(0, 10),
              saveWeeklyPlanBoList: [{
                departmentId: i.departmentId,
                departmentName: i.departmentName,
                planContent: i.planContent,
                place: i.place,
                time: i.time
              }]
            })
          } else {
            let isSameTime = false
            let tempObj1 = {}
            let index
            arr.forEach((i2, index2) => {
              console.log(i2.planDate)
              console.log(i.planDate.slice(0, 10))
              if (i2.planDate == i.planDate.slice(0, 10)) {
                tempObj1 = {
                  departmentId: i.departmentId,
                  departmentName: i.departmentName,
                  planContent: i.planContent,
                  place: i.place,
                  time: i.time
                }
                index = index2
                isSameTime = true
              } else {
                tempObj1 = i
              }
            })
            if (isSameTime) {
              arr[index].saveWeeklyPlanBoList.push(tempObj1)
            } else {
              arr.push({
                planDate: tempObj1.planDate.slice(0, 10),
                saveWeeklyPlanBoList: [{
                  departmentId: tempObj1.departmentId,
                  departmentName: tempObj1.departmentName,
                  planContent: tempObj1.planContent,
                  place: tempObj1.place,
                  time: tempObj1.time
                }]
              })
            }
          }
        })
        console.log(arr)
        res.data.list = arr
        setDetail_data(res.data)
        console.log(res.data)
        setGap_day(arr)
        setTypeName(res.data.partitionName)
        setTitle(res.data.title)
        setTime_val(`${res.data.startDate?.slice(0, 10).replaceAll('-', '/')}~${res.data.endDate?.slice(0, 10).replaceAll('-', '/')}`)
        setTypeId(res.data.partitionId)
      }
    })
  }
  const [weeklyRoutineId, setWeeklyRoutineId] = useState('')
  useEffect(() => {
    let params = props.tid.split('?')[1]
    console.log(params)
    if (params.includes('partitionId')) {
      params = params.split('&')[1].split('=')[1]
    } else {
      params = params.split('&')[0].split('=')[1]
    }
    console.log(params)
    if (params != '0') {
      console.log(params)
      getDetailData(params)
      setWeeklyRoutineId(params)
      setEdit_add('edit')
      document.title = '编辑周行事历'
    } else {
      setEdit_add('add')
      document.title = '添加周行事历'
    }
  }, [])

  //获取全部类型
  const getTypeList = () => {
    let url = 'api/weekly/general/partition/list'
    HttpGet({
      url,
      data: {
        schoolId: storage.get('schoolId') || Utils.getQueryVariable('schoolId') || userInfo.schoolId,
        schoolLevel: storage.get('schoolLevel') || userInfo.schoolLevel
      }
    }).then((res) => {
      if (res.code == 200) {
        let data = res.data;
        // data.forEach(item => {
        //   item.optionList = [
        //     { text: '编辑', onClick: () => operation('edit', item), className: 'edit' },
        //     { text: '删除', onClick: () => operation('del', item), className: 'delete' }]
        // })
        setTypeList(data)
        let params = props.tid.split('?')[1]
        console.log(params)

        params = params.split('&')[0].split('=')[1]
        console.log(params)
        if (params != '0') {
          return
        } else {
          data.forEach(i => {
            if (i.partitionId == window.nowCurrentType) {
              setTypeName(i.partitionName)
              setTypeId(i.partitionId)
            }
          })
        }
      }
    })
  }

  const [arrangeList, setArrangeList] = useState([])
  const [arrangeList2, setArrangeList2] = useState([])
  // 获取部门
  const getArrangeist = () => {
    let url = 'api/common/organize'
    HttpGet({
      url,
      data: {
        schoolId: storage.get('schoolId') || Utils.getQueryVariable('schoolId') || userInfo.schoolId,
      }
    }).then((res) => {
      if (res.code == 200) {
        let data = res.data;
        setArrangeList(data)
        setArrangeList2(data)
      }
    })
  }

  //类型列表
  const handlePopLayer = (type, full = "") => {
    let arr = typeList.concat([])
    if (type == 'open') {
      setVisible(true)
    } else {
      setVisible(false)
    }
  }
  //选择类型
  const changeType = (obj, e) => {
    console.log(obj)
    console.log(e)
    // let target = e.target;
    // if (target.classList.contains('edit') || target.classList.contains('delete')) {
    //   return;
    // }
    setTypeId(obj.partitionId);
    setTypeName(obj.partitionName);
    handlePopLayer('close')
  }

  //发布周行事历
  const createNotice = (autoSave = false) => {
    console.log(gap_day)
    // if (autoSave == true) {
    //   let params = []
    //   gap_day.forEach((i, index) => {
    //     i.saveWeeklyPlanBoList.forEach((i2, index2) => {
    //       params.push({
    //         dateStr: `${i.planDate.slice(5, 7)}月${i.planDate.slice(8)}日`,
    //         departmentId: i2.departmentId,
    //         departmentName: i2.departmentName,
    //         planContent: i2.planContent,
    //         planDate: `${i.planDate} 00:00:00`,
    //         rowSpan: i.saveWeeklyPlanBoList.length,
    //       })
    //     })
    //   })
    //   console.log(params)
    //   let url = 'api/weekly/general/cache/save';

    //   HttpPost({
    //     url,
    //     data: {
    //       endDate: `2024-10-21 23:59:59`,
    //       partitionId: typeId,
    //       partitionName: typeName,
    //       title: title,
    //       startDate: `2024-10-18 00:00:00`,
    //       saveWeeklyPlanBoList: params,
    //       userId: storage.get('UserID') || userInfo.userId,
    //       userName: storage.get('UserName') || userInfo.userName,
    //       schoolId: storage.get('schoolId') || userInfo.schoolId,
    //       weeklyRoutineId: ''
    //       // schoolName: storage.get('schoolName') || decodeURIComponent(userInfo.schoolName),
    //     }
    //   }).then((data) => {
    //   })
    //   return
    // }
    if (typeName.length == 0) {
      Taro.showToast({
        title: '请选择所属分区',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (title == '') {
      Taro.showToast({
        title: '请输入标题！',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (time_val.length == 0) {
      Taro.showToast({
        title: '请选择起止时间！',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    let flag = false
    gap_day.forEach((i, index) => {
      console.log(i)
      if (i.saveWeeklyPlanBoList.length == 0) {
        flag = true
        Taro.showToast({
          title: '请先编辑事务安排！',
          icon: 'none',
          duration: 2000
        })
        return;
      }
    })
    if (flag) {
      return
    }
    let params = []
    gap_day.forEach((i, index) => {
      i.saveWeeklyPlanBoList.forEach((i2, index2) => {
        params.push({
          dateStr: `${i.planDate.slice(5, 7)}月${i.planDate.slice(8)}日`,
          departmentId: i2.departmentId,
          departmentName: i2.departmentName,
          planContent: i2.planContent,
          place: i2.place,
          time: i2.time,
          planDate: `${i.planDate} 00:00:00`,
          rowSpan: i.saveWeeklyPlanBoList.length,
        })
      })
    })
    console.log(params)
    let url = 'api/weekly/general/created/save';

    Taro.showLoading({
      title: '正在发布~',
    })
    HttpPost({
      url,
      data: {
        endDate: `${time_val.slice(11).replaceAll('/', '-')} 23:59:59`,
        partitionId: typeId,
        partitionName: typeName,
        title: title,
        startDate: `${time_val.slice(0, 10).replaceAll('/', '-')} 00:00:00`,
        saveWeeklyPlanBoList: params,
        userId: storage.get('UserID') || userInfo.userId,
        userName: storage.get('UserName') || userInfo.userName,
        schoolId: storage.get('schoolId') || userInfo.schoolId,
        weeklyRoutineId: edit_add == 'edit' ? weeklyRoutineId : ''
        // schoolName: storage.get('schoolName') || decodeURIComponent(userInfo.schoolName),
      }
    }).then((data) => {
      if (data.code == 200) {
        // Taro.navigateBack({ delta: 1 })
        window.nowCurrentType = typeId
        Taro.redirectTo({
          url: `/pages/newsInfoApp/index?partitionId=${typeId}`
        })
        Taro.hideLoading();
        setTimeout(() => {
          Taro.showToast({
            title: '发布成功~',
            duration: 2000
          })
        }, 500);
      }
    })
  }



  // 操作常用设置
  const operation = (type, item) => {
    switch (type) {
      case 'edit': setOldValue(item.newTypeName), setInputPopOpen(true), setOldItem(item);
        break;
      case 'add': setOldValue(''), setOldItem(''), setInputPopOpenNew(true);
        break;
      case 'del':
        Taro.showModal({
          title: '是否删除该资讯类型？',
          content: '该类型下所有资讯也将被删除！',
          success: function (res) {
            if (res.confirm) {
              HttpDelete({
                url: '/api/news/type/delete?typeId=' + item.newsTypeId,
              }).then((result) => {
                if (result.code === '200') {
                  getTypeList();
                  Taro.showToast({
                    title: '删除成功',
                    duration: 2000,
                    mask: true
                  })
                }
              })
            } else if (res.cancel) {
              // console.log('用户点击取消')
            }
          }
        })
        break;
    }

  }

  const goBack = () => {
    Taro.redirectTo({
      url: '/pages/newsInfoApp/index'
    })
  }

  const initWxSdk = async () => {
    const params = getWxSDKParams(['previewImage', 'getLocation'])
    wx.config(params);
    wx.ready(function () {
      // config信息验证后会执行 ready 方法，所有接口调用都必须在 config 接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在 ready 函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在 ready 函数中。
      console.log('ready')
    });
    wx.error(function (res) {
      // config信息验证失败会执行 error 函数，如签名过期导致验证失败，具体错误信息可以打开 config 的debug模式查看，也可以在返回的 res 参数中查看，对于 SPA 可以在这里更新签名。
      console.log(res)
    });
  }

  useEffect(() => {
    if (window.__wxjs_environment == 'miniprogram') {
      initWxSdk()
    }
    getCommonData()
    getTypeList()
    getArrangeist()
    return () => {
      if (Utils.getSystemInfo() == 'weapp') {
        window.getNoticeList && typeof window.getNoticeList == 'function' && window.getNoticeList()
      }
    }
  }, []);

  const publishEdu = () => {
    setToEdu(!toEdu);
  }

  const [visible2, setVisible2] = useState(false)

  const [time_val, setTime_val] = useState('')

  const [gap_day, setGap_day] = useState([])

  // 编辑按钮
  const [nowBeSelectPlan, setNowBeSelectPlan] = useState({})
  const [popupVisible, setPopupVisible] = useState(false)
  const [temp_saveWeeklyPlanBoList, setTemp_saveWeeklyPlanBoList] = useState([])
  const changePopupVisible = (index) => {
    setPopupVisible(!popupVisible)
    if (edit_add == 'edit') {
      gap_day.forEach((i, index) => {
        i.index = index
      })
    }
    // let tempData = gap_day[index]
    setNowBeSelectPlan(gap_day[index])
    if (gap_day[index].saveWeeklyPlanBoList.length <= 0) {
      setTemp_saveWeeklyPlanBoList([{
        departmentName: '',
        planContent: '',
        place: "",
        time: ""
      }])
    } else {
      setTemp_saveWeeklyPlanBoList(gap_day[index].saveWeeklyPlanBoList)
    }
    console.log(gap_day[index])
  }

  const [arrange_popup, setArrange_popup] = useState(false)

  const arrange_popup_visible = (index) => {
    console.log(index)
    nowArrangeIndex = index
    setArrange_popup(true)
    console.log(nowArrangeIndex)
  }

  const selectArrange = (item) => {
    console.log(item)
    console.log(nowArrangeIndex)
    console.log(temp_saveWeeklyPlanBoList)
    temp_saveWeeklyPlanBoList[nowArrangeIndex].departmentId = item.departmentId
    temp_saveWeeklyPlanBoList[nowArrangeIndex].departmentName = item.departmentName

    setArrange_popup(false)
  }

  const changePlanContent = useCallback((val, index) => {
    temp_saveWeeklyPlanBoList[index].planContent = val
  }, [temp_saveWeeklyPlanBoList])

  const changePlace = useCallback((val, index) => {
    temp_saveWeeklyPlanBoList[index].place = val
  }, [temp_saveWeeklyPlanBoList])

  const showTimePicker = useCallback((index) => {
    const hours = Array.from({ length: 24 }, (_, i) => ({
      label: i.toString().padStart(2, '0'),
      value: i.toString().padStart(2, '0')
    }))

    const minutes = Array.from({ length: 60 }, (_, i) => ({
      label: i.toString().padStart(2, '0'),
      value: i.toString().padStart(2, '0')
    }))
    console.log(temp_saveWeeklyPlanBoList)
    console.log(index)
    Picker.prompt({
      columns: [hours, minutes],
      onConfirm: (value) => {
        const timeString = `${value[0]}:${value[1]}`
        setTimeValue(timeString)
        temp_saveWeeklyPlanBoList[index].time = timeString
      },
    })
  }, [temp_saveWeeklyPlanBoList])

  const okEdit = () => {
    console.log(temp_saveWeeklyPlanBoList)
    console.log(gap_day)
    console.log(nowBeSelectPlan)
    let tempdata = [...gap_day]
    let flag = false
    temp_saveWeeklyPlanBoList.forEach((i, index) => {
      if (i.departmentName == '' || i.planContent == '') {
        flag = true
      }
    })
    if (flag) {
      Taro.showToast({
        title: '请选择部门名称和填写事务安排',
        icon: 'none',
        duration: 2000
      })
      return
    } else {
      temp_saveWeeklyPlanBoList.forEach((i, index) => {
        tempdata[nowBeSelectPlan.index].saveWeeklyPlanBoList[index] = i
      })
      setGap_day(tempdata)
      setPopupVisible(false)
    }
  }

  const addArrange = () => {
    let temp = [...temp_saveWeeklyPlanBoList]
    temp.push({
      departmentName: '',
      planContent: '',
      time: "",
      place: ""
    })
    setTemp_saveWeeklyPlanBoList(temp)
  }

  const deleteRow = (index) => {
    console.log(index)
    if (temp_saveWeeklyPlanBoList.length == 1) {
      Toast.show({
        content: '至少保留一行！',
        duration: 2000,
        position: 'center' // 可以尝试不同位置：top, bottom, center
      })
      return
    }
    let tempdata = [...gap_day]
    // temp_saveWeeklyPlanBoList.forEach((i, index) => {
    // })

    console.log(temp_saveWeeklyPlanBoList)
    let tempData = [...temp_saveWeeklyPlanBoList]
    tempData.splice(index, 1)
    tempdata[nowBeSelectPlan.index].saveWeeklyPlanBoList = tempData
    setGap_day(tempdata)
    setTemp_saveWeeklyPlanBoList(tempData)
    // setGap_day(tempData)
  }

  const gotoParitionSetting = () => {
    handlePopLayer('close',)
    let url = '/pages/newsInfoApp/partitionSetting/index'
    Taro.navigateTo({
      url
    })
  }

  const arrangeSearchFunc = _.debounce((val) => {
    if (!val) {
      setArrangeList(arrangeList2)
      return
    }
    let tempData = []
    arrangeList.forEach(i => {
      console.log(i.departmentName)
      console.log(i.departmentName.includes(val))
      if (i.departmentName.includes(val)) {
        tempData.push(i)
      }
    })
    setArrangeList(tempData)
  }, 1000)

  // 自动保存数据
  const autoSaveDataFunc = () => {
    createNotice(true)
  }

  // useEffect(() => {
  //   setInterval(() => {
  //     autoSaveDataFunc()
  //   }, 5000)
  // }, [])

  return (
    <View className="newsTitle">
      {
        Utils.getQueryVariable('env') == 'weapp' || window.__wxjs_environment == 'miniprogram' ?
          "" :
          <Header
            className='header-top'
            mainTitle={edit_add == 'edit' ? '编辑周行事历' : '添加周行事历'}
            mainTitleBlod={false}
            isTitlePositionLeft={true}
            needMainIcon={process.env.TARO_ENV == 'weapp' ? false : true}
            onClick={Taro.getCurrentInstance().router?.params.from ? goBack : ''}
          />
      }

      <View className="header">
        <View className='select_type'>
          <LgCell
            title={<Text><Text className='must-fill'></Text>所属分区</Text>}
            content={
              typeName ? <div style={{ color: '#000000' }}>{typeName}</div> : '请选择'
            }
            showIcon={true}
            onClick={() => {
              handlePopLayer('open');
            }}
            type='A'
          ></LgCell>

          <LgPopLayer
            position="bottom"
            confirm={() => { handlePopLayer('close',) }}
            showLayer={() => handlePopLayer('close',)}
            title={'分区选择'}
            showClose
            isOpen={visible}>
            {
              typeList.length < 12 ?
                <View>
                  <View className='type-add' onClick={() => gotoParitionSetting()}>分区设置</View>
                  <View className='type-add-shu'>|</View>
                </View>
                : ''
            }
            {
              typeList.length > 0 ?
                typeList.map((item, index) => {
                  return (
                    <View className="kind_one" key={index} onClick={(e) => changeType(item, e)}>
                      {/* <LgSlide data={item?.optionList} canSlide={true} key={visible + (item?.newsTypeId)}> */}
                      <View style={{ width: '100vw', marginRight: '18px' }}>
                        {item.partitionName}
                      </View>
                      {/* </LgSlide> */}
                    </View>
                  )
                }) : ''
            }
          </LgPopLayer>
        </View>
        <View className="line"></View>
        <div style={{ paddingRight: '20px' }}>
          <LgInput
            value={title}
            maxLength={30}
            type="A"
            inputName={<Text><Text className='must-fill'></Text>标题</Text>}
            placeholder="请输入..."
            onChange={value => setTitle(value)}
          ></LgInput>
        </div>
        <View className="line"></View>

        <List style={{ margin: '0 5px' }}>
          <List.Item
            onClick={() => {
              setVisible2(true)
            }}
          >
            起止时间
            <span style={{ float: 'right' }}>{time_val}</span>
          </List.Item>
        </List>

        <div className='line2'></div>

        <View>
          <div className='table_title'>事务安排
            {
              gap_day.length > 0 ? <span>(共<span style={{ color: 'rgb(51,51,51)' }}>{gap_day.length}</span>项)</span> : ''
            }
            {/* <span>(共<span style={{ color: 'rgb(51,51,51)' }}>{gap_day.length}</span>项)</span> */}
          </div>
          {
            gap_day.length > 0 ? <>
              {/* <div className='table_title'>事务安排<span>(共<span style={{ color: 'rgb(51,51,51)' }}>8</span>项)</span></div> */}
              <div className='table_box'>
                <div className='table_header'>
                  <div className='time'>时间</div>
                  <div className='arrange'>事务安排</div>
                  <div className='operation'>操作</div>
                </div>
                <div className='table_list' style={{ maxHeight: '48vh' }}>
                  {
                    gap_day.length > 0 ? <>
                      {
                        gap_day.map((i, index) => {
                          return (
                            <div className='table_item'>
                              <div className='table_item_time'>{`${i.planDate.slice(5, 7)}月${i.planDate.slice(8)}日`}
                                <div style={{ color: "rgb(153,153,153)" }}>({weekdays[new Date(moment(i.planDate).format("yyyy-MM-DD")).getDay()]})</div>
                              </div>
                              <div className='table_item_arrange'>
                                {
                                  i.saveWeeklyPlanBoList.length > 0 ? <>
                                    {
                                      i.saveWeeklyPlanBoList.map(i2 => {
                                        return (
                                          <div className='arrange_item'>
                                            <div className='content1'>
                                              <div className='department'>{i2.departmentName}</div>
                                              <div className='arrange_content'>{i2?.planContent ? i2.planContent.length < 8 ? i2.planContent : i2.planContent.slice(0, 8) + "..." : '--'}</div>
                                            </div>
                                            <div className='content2'>
                                              <div>时间：{i2?.time ? i2.time : '--'}</div>
                                              <div className='place'>地点：{i2?.place ? i2.place.length < 8 ? i2.place : i2.place.slice(0, 8) + "..." : '--'}</div>
                                            </div>
                                            {/* <div className='department'>{i2.departmentName ? i2.departmentName : ''}</div>
                                            <div className='arrange_content'>{i2.planContent}</div> */}
                                          </div>
                                        )
                                      })
                                    }
                                  </> : <div className='arrange_item'></div>
                                }
                              </div>
                              <div onClick={() => { changePopupVisible(index) }} className='table_item_operation'>编辑</div>
                            </div>
                          )

                        })
                      }
                    </> : ''
                  }
                </div>
              </div>
            </> : <div className='empty'>
              <div className='empty_img'></div>
              <div className='empty_text'>请选择起止时间</div>
            </div>
          }
        </View>

      </View>

      <View className="index_footer">
        <LgButton className="send_btn cancel" type='D' width={324} height={88} onClick={() => {
          Taro.redirectTo({
            url: `/pages/newsInfoApp/index`
          })
        }}> 取消</LgButton>
        <LgButton className="send_btn ok" type='B' width={324} height={88} onClick={() => createNotice()} >确定</LgButton>
      </View>

      <CalendarPicker
        visible={visible2}
        // defaultValue={defaultRange}
        selectionMode='range'
        onClose={() => setVisible2(false)}
        onMaskClick={() => setVisible2(false)}
        onChange={val => {
          console.log(val)
          console.log(timeToString(val[0]))
          console.log(timeToString(val[1]))
          let date = timeToString(val[0]) + '~' + timeToString(val[1])
          setTime_val(date)
        }}
        onConfirm={val => {
          let date = timeToString(val[0]) + '~' + timeToString(val[1])
          setTime_val(date)
          setGap_day(getDayAll(timeToString(val[0]), timeToString(val[1])))
        }}
      />

      <Popup
        visible={popupVisible}
        showCloseButton={true}
        onMaskClick={() => {
          setPopupVisible(false)
        }}
        onClose={() => {
          setPopupVisible(false)
        }}
        bodyStyle={{
          borderTopLeftRadius: '8px',
          borderTopRightRadius: '8px',
          minHeight: '60vh',
        }}
      >
        <div className='edit_popup'>
          <div className='edit_time'>编辑事务<span>({nowBeSelectPlan.planDate})</span></div>
          <div className='line'></div>
          <div className='arrange_num'>共<span>{nowBeSelectPlan.saveWeeklyPlanBoList?.length != 0 ? nowBeSelectPlan.saveWeeklyPlanBoList?.length : 1}</span>条事务安排</div>
          <div className='table_box'>
            <div className='table_header'>
              <div className='time'></div>
              <div className='arrange'>事务安排</div>
              <div className='operation'>操作</div>
            </div>
            <div className='table_list2' style={{ maxHeight: '25vh' }}>
              {
                <>
                  {
                    temp_saveWeeklyPlanBoList.map((i, index) => {
                      return (
                        <div className='table_item'>
                          <div className='table_item_time'>
                            <Button
                              style={{ width: "92%" }}
                              onClick={() => {
                                // setVisible22(true)
                                arrange_popup_visible(index)
                              }}
                            >
                              <div style={{ textAlign: "left", fontSize: "16px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                                <div style={{ marginLeft: "-8px" }}>{i.departmentName ? i.departmentName : <span style={{ color: "rgb(204,204,204)" }}>选择部门</span>}</div>
                                <div style={{ width: "14px", height: "14px", marginRight: "-8px" }}>
                                  <img style={{ width: "100%" }} src={require('../images/down2.png')}></img>
                                </div>
                              </div>
                            </Button>
                            <Button
                              style={{ marginTop: "12px", width: "92%" }}
                              onClick={() => { showTimePicker(index) }}
                            >
                              <div style={{ textAlign: "left", fontSize: "16px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                                <div style={{ marginLeft: "-8px" }}>{i.time ? i.time : <span style={{ color: "rgb(204,204,204)" }}>选择时间</span>}</div>
                                <div style={{ width: "18px", height: "18px", marginRight: "-8px" }}>
                                  <img style={{ width: "100%" }} src={require('../images/time2.png')}></img>
                                </div>
                              </div>

                            </Button>
                            {/* <VirtualInput
                              // key={nowBeSelectPlan.index}
                              style={{ width: '100%' }}
                              placeholder='请选择...'
                              value={i.departmentName}
                              onClick={() => { arrange_popup_visible(index) }}
                            /> */}
                          </div>
                          <div className='table_item_arrange'>
                            <div className='arrange_item_edit'>
                              <div className='arrange_item1'>
                                <Input
                                  key={nowBeSelectPlan.index + 'id'}
                                  placeholder={i.planContent ? i.planContent : '请输入内容...'}
                                  // value={i.planContent}
                                  onChange={val => {
                                    changePlanContent(val, index)
                                  }}
                                />
                              </div>
                              <div className='arrange_item2'>
                                <Input
                                  key={nowBeSelectPlan.index + 'id'}
                                  placeholder={i.place ? i.place : '请输入地点...'}
                                  // value={i.planContent}
                                  onChange={val => {
                                    changePlace(val, index)
                                  }}
                                />
                              </div>
                            </div>
                          </div>
                          <div onClick={() => { deleteRow(index) }} className='table_item_operation_delete'>删除</div>
                        </div>
                      )
                    })
                  }
                </>
              }
            </div>
          </div>
          <div className='add_arrange'>
            <span onClick={() => { addArrange() }} className='add_btn'><i className='myTable_addCase_icon'></i>新增事务</span>
          </div>
        </div>
        <div className="index_footer">
          <LgButton className="send_btn cancel" type='D' width={324} height={88} onClick={() => setPopupVisible(false)}> 取消</LgButton>
          <LgButton className="send_btn ok" style={{ marginLeft: '12px' }} type='B' width={324} height={88} onClick={() => okEdit()} >确定</LgButton>
        </div>
      </Popup>
      <Popup
        visible={arrange_popup}
        onMaskClick={() => {
          setArrange_popup(false)
        }}
        bodyStyle={{
          borderTopLeftRadius: '8px',
          borderTopRightRadius: '8px',
          height: '40vh',
          overflowY: 'auto'
        }}
      >
        <div className='arrange_search'><SearchBar onChange={(val) => { arrangeSearchFunc(val) }} placeholder='请输入内容' /></div>
        {
          arrangeList.map(i => {
            return (
              <div onClick={() => { selectArrange(i) }} className='select_arrange_item'>{i.departmentName}</div>
            )
          })
        }
      </Popup>
    </View>
  )
}

const mainProps = ({ commonData }) => {
  // console.log(commonData, 'commonData');

  return {
    userInfo: commonData.userInfo,
    env: commonData.env,
    noticeAddr: commonData.noticeAddr,
    baseUrl: commonData.baseUrl,
    systemInfo1: commonData.systemInfo,
  }
}

export default connect(mainProps)(App);
